<template>
  <div :class="{fullscreen:fullscreen}" class="tinymce-container" :style="{width:containerWidth}">
    <textarea readonly="readonly" :id="tinymceId" class="tinymce-textarea" />
    <div class="editor-custom-btn-container">
      <editorImage color="#1890ff" class="editor-upload-btn" @successCBK="imageSuccessCBK" />
    </div>
  </div>
</template>

<script>
/**
 * docs:
 * https://panjiachen.github.io/vue-element-admin-site/feature/component/rich-editor.html#tinymce
 */
import editorImage from './components/EditorImage'
import plugins from './plugins'
import toolbar from './toolbar'
import load from './dynamicLoadScript'

// why use this cdn, detail see https://github.com/PanJiaChen/tinymce-all-in-one
//const tinymceCDN = 'https://cdn.jsdelivr.net/npm/tinymce@5.0.11/tinymce.min.js'
const tinymceCDN = 'https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.3/tinymce.min.js'

export default {
  name: 'Tinymce',
  components: { editorImage },
  props: {
    id: {
      type: String,
      default: function() {
        return 'vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '')
      }
    },
    value: {
      type: String,
      default: ''
    },
    toolbar: {
      type: Array,
      required: false,
      default() {
        return []
      }
    },
    menubar: {
      type: String,
      default: ''
    },
    height: {
      type: [Number, String],
      required: false,
      default: 360
    },
    width: {
      type: [Number, String],
      required: false,
      default: 'auto'
    },
  },
  data() {
    return {
      hasChange: false,
      hasInit: false,
      tinymceId: this.id,
      fullscreen: false,
      languageTypeList: {
        'zh': 'zh_CN'
      }
    }
  },
  computed: {
    language() {
      return this.languageTypeList[this.$store.getters.language]
    },
    containerWidth() {
      const width = this.width
      if (/^[\d]+(\.[\d]+)?$/.test(width)) { // matches `100`, `'100'`
        return `${width}px`
      }
      return width
    }
  },
  watch: {
    value(val) {
      if (!this.hasChange && this.hasInit) {
        this.$nextTick(() =>
          window.tinymce.get(this.tinymceId).setContent(val || ''))
      }
    },
    language() {
      this.destroyTinymce()
      this.$nextTick(() => this.initTinymce())
    }
  },
  created() {
  },
  mounted() {
    console.log("mounted")
    this.init()
  },
  activated() {
    console.log("activated")
    if (window.tinymce) {
      console.log("activated initTinymce")
      this.initTinymce()
    }
  },
  deactivated() {
    console.log("deactivated")
    this.destroyTinymce()
  },
  destroyed() {
    console.log("destroyed")
	console.log(this.value)
    if (this.value !== '') { // 避免没数据时报错
      this.destroyTinymce()
    }
  },
  methods: {
    init() {
      // dynamic load tinymce from cdn
      load(tinymceCDN, (err) => {
        if (err) {
          this.$message.error(err.message)
          return
        }
        console.log("load")

        window.tinymce.PluginManager.add('letterspacing', function(editor, url, $) {
          editor.on('init', function() {
            editor.formatter.register({
              letterspacing: {
                inline: 'span',
                styles: {
                  'letter-spacing': '%value'
                }
              }
            })
          })

          editor.addButton('letterspacingselect', function() {
            var items = [],
              defaultLetterSpacingFormats = '0 0.5pt 1pt 1.5pt 2pt 3pt'
            var letterspacing_formats = editor.settings.letterspacing_formats || defaultLetterSpacingFormats
            letterspacing_formats.split(' ').forEach(function(item) {
              var text = item,
                value = item
              // Allow text=value for line-height formats
              var values = item.split('=')
              if (values.length > 1) {
                text = values[0]
                value = values[1]
              }
              items.push({
                text: text,
                value: value
              })
            })
            return {
              type: 'listbox',
              text: '字间距',
              tooltip: '字间距',
              values: items,
              fixedWidth: true,
              onPostRender: function() {
                var self = this
                editor.on('nodeChange', function(e) {
                  var formatName = 'letterspacing'
                  var formatter = editor.formatter
                  var value = null
                  e.parents.forEach(function(node) {
                    items.forEach(function(item) {
                      if (formatName) {
                        if (formatter.matchNode(node, formatName, {
                            value: item.value
                          })) {
                          value = item.value
                        }
                      } else {
                        if (formatter.matchNode(node, item.value)) {
                          value = item.value
                        }
                      }
                      if (value) {
                        return false
                      }
                    })
                    if (value) {
                      return false
                    }
                  })
                  self.value(value)
                })
              },
              onselect: function(e) {
                window.tinymce.activeEditor.formatter.apply('letterspacing', {
                  value: this.value()
                })
              }
            }
          })
        })

        window.tinymce.PluginManager.add('lineheight', function(editor, url, $) {
          editor.on('init', function() {
            editor.formatter.register({
              lineheight: {
                selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table',
                styles: { 'line-height': '%value' }
              }
            })
          })

          editor.addButton('lineheight', function() {
            var items = [],
              defaultLetterSpacingFormats = '0 1 1.1 1.2 1.3 1.4 1.5 1.6 1.75 1.8 2 3 4 5'
            var letterspacing_formats = editor.settings.letterspacing_formats || defaultLetterSpacingFormats
            letterspacing_formats.split(' ').forEach(function(item) {
              var text = item,
                value = item
              // Allow text=value for line-height formats
              var values = item.split('=')
              if (values.length > 1) {
                text = values[0]
                value = values[1]
              }
              items.push({
                text: text,
                value: value
              })
            })
            return {
              type: 'listbox',
              text: '行间距',
              tooltip: '行间距',
              values: items,
              fixedWidth: true,
              onPostRender: function() {
                var self = this
                editor.on('nodeChange', function(e) {
                  var formatName = 'lineheight'
                  var formatter = editor.formatter
                  var value = null
                  e.parents.forEach(function(node) {
                    items.forEach(function(item) {
                      if (formatName) {
                        if (formatter.matchNode(node, formatName, {
                            value: item.value
                          })) {
                          value = item.value
                        }
                      } else {
                        if (formatter.matchNode(node, item.value)) {
                          value = item.value
                        }
                      }
                      if (value) {
                        return false
                      }
                    })
                    if (value) {
                      return false
                    }
                  })
                  self.value(value)
                })
              },
              onselect: function(e) {
                window.tinymce.activeEditor.formatter.apply('lineheight', {
                  value: this.value()
                })
              }
            }
          })
        })

        this.initTinymce()

      })
    },
    initTinymce() {
      const _this = this
      console.log("initTinymce")
      window.tinymce.init({
        language: 'zh_CN',
        selector: `#${this.tinymceId}`,
        height: this.height,
        body_class: 'panel-body ',
        object_resizing: false,
        toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
        menubar: this.menubar,
        plugins: plugins,
        end_container_on_empty_block: true,
        powerpaste_word_import: 'clean',
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'default',
        imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
        default_link_target: '_blank',
        link_title: false,
        nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
        init_instance_callback: editor => {
          console.log("init_instance_callback")
          if (_this.value) {
            editor.setContent(_this.value)
          }
          _this.hasInit = true
          editor.on('NodeChange Change KeyUp SetContent', () => {
            this.hasChange = true
            this.$emit('input', editor.getContent())
          })


        },
        setup(editor) {
          editor.on('FullscreenStateChanged', (e) => {
            console.log(e)
            console.log('富文本')
            _this.fullscreen = e.state
          })
        }
        // 整合七牛上传
        // images_dataimg_filter(img) {
        //   setTimeout(() => {
        //     const $image = $(img);
        //     $image.removeAttr('width');
        //     $image.removeAttr('height');
        //     if ($image[0].height && $image[0].width) {
        //       $image.attr('data-wscntype', 'image');
        //       $image.attr('data-wscnh', $image[0].height);
        //       $image.attr('data-wscnw', $image[0].width);
        //       $image.addClass('wscnph');
        //     }
        //   }, 0);
        //   return img
        // },
        // images_upload_handler(blobInfo, success, failure, progress) {
        //   progress(0);
        //   const token = _this.$store.getters.token;
        //   getToken(token).then(response => {
        //     const url = response.data.qiniu_url;
        //     const formData = new FormData();
        //     formData.append('token', response.data.qiniu_token);
        //     formData.append('key', response.data.qiniu_key);
        //     formData.append('file', blobInfo.blob(), url);
        //     upload(formData).then(() => {
        //       success(url);
        //       progress(100);
        //     })
        //   }).catch(err => {
        //     failure('出现未知问题，刷新页面，或者联系程序员')
        //     console.log(err);
        //   });
        // },
      })
    },
    destroyTinymce() {
      const tinymce = window.tinymce.get(this.tinymceId)
      if (this.fullscreen) {
        tinymce.execCommand('mceFullScreen')
      }

      if (tinymce) {
        tinymce.destroy()
      }
    },
    setContent(value) {
      window.tinymce.get(this.tinymceId).setContent(value)
    },
    getContent() {
      window.tinymce.get(this.tinymceId).getContent()
    },
    imageSuccessCBK(arr) {
      const _this = this
      arr.forEach(v => {
        window.tinymce.get(_this.tinymceId).insertContent(`<img class="wscnph" style="width:100%;display:block" src="${v.url}" >`)
      })
    }
  }
}
</script>

<style scoped>
.tinymce-container {
  position: relative;
  line-height: normal;
}
.tinymce-container>>>.mce-fullscreen {
  z-index: 10000;
}
.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}
.editor-custom-btn-container {
  position: absolute;
  right: 4px;
  top: 4px;
  /*z-index: 2005;*/
}
.fullscreen .editor-custom-btn-container {
  z-index: 10000;
  position: fixed;
}
.editor-upload-btn {
  display: inline-block;
}
/deep/.wscnph{
  display: block;
}
</style>
